#include "view.h"

#include <QDebug>

View::View(Ui::BimosControl *uiBimosWindow):ui(uiBimosWindow) {
    initialize();
    setupPressureTab();
    setupEvacuateTab();
    setupPrepressureTab();
}

void View::initialize() {
    xValue = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;

    // 1 second step
    plotXStep = 5;
    // show 30 seconds default
    plotXRange = 30;

    QColor color[] = {Qt::cyan, Qt::darkBlue,
                      Qt::darkCyan, Qt::darkGray,
                      Qt::darkGreen,Qt::darkMagenta,
                      Qt::darkRed,Qt::darkYellow,
                      Qt::gray,Qt::green,
                      Qt::lightGray,Qt::magenta,
                      Qt::red,Qt::yellow};

    ui->customPlot->legend->setVisible(true);
    QFont legendFont = font();  // start out with MainWindow's font..
    legendFont.setPointSize(9); // and make a bit smaller for legend
    ui->customPlot->legend->setFont(legendFont);
    ui->customPlot->legend->setPositionStyle(QCPLegend::psLeft);
    ui->customPlot->legend->setBrush(QBrush(QColor(255,255,255,230)));
    ui->customPlot->legend->setItemSpacing(0);
    ui->customPlot->legend->setVisible(false);
    ui->customPlot->setAutoAddPlottableToLegend(false);


    // TODO get maxnumberofSensors
    for (int i = 0; i < SENSOR_COUNT; i++) {
        ui->customPlot->addGraph();
        ui->customPlot->graph()->setVisible(false);
        ui->customPlot->graph()->setPen(QPen(color[i]));
        ui->customPlot->graph()->setAntialiasedFill(false);
        ui->customPlot->graph()->setName("Sensor " + QString::number(i+1));
    }

    ui->customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    ui->customPlot->xAxis->setDateTimeFormat("hh:mm:ss");
    ui->customPlot->xAxis->setAutoTickStep(false);
    ui->customPlot->xAxis->setTickStep(plotXStep);
    ui->customPlot->xAxis->setLabel("Zeit [hh:mm:ss]");
    ui->customPlot->yAxis->setLabel("Druck [mBar]");

    // y axis on top
    ui->customPlot->setupFullAxesBox();

    // y axis bottom / top sync
    connect(ui->customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)),
            ui->customPlot->xAxis2, SLOT(setRange(QCPRange)));
    connect(ui->customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)),
            ui->customPlot->yAxis2, SLOT(setRange(QCPRange)));

    // inital range
    ui->customPlot->yAxis->setRange(0, 1);

    redText = new QPalette;
    normalText = new QPalette;
    redText->setColor(QPalette::WindowText, Qt::red);
    normalText->setColor(QPalette::WindowText, Qt::black);


}

void View::setupPressureTab() {
    setupHorizontalLines();
    setupPressureTabLabels();
}

void View::setupEvacuateTab() {
    setupEvacuateTabLabelsAndButtons();
}
void View::setupPrepressureTab() {
    setupPrepressureTabLabelsAndButtons();
}


void View::draw(BimosSensorPressure *sensor) {
    // set text labels

    labelPressureValues[sensor->getOrdinal()]->setText(
                "Mittelwert: " + QString::number(sensor->getVolt(),'f',3) +
                "[V]\n rel. Druck:" + QString::number(sensor->getPressure(),'f',2) +
                "[mBar]\n Gasertrag:" + QString::number(sensor->getPressure()-ABSOLUTE_PRESSURE_AIR,'f',2)
                );
    // add data to graph
    ui->customPlot->graph(sensor->getOrdinal())->addData(xValue,sensor->getPressure());
    // set text red if not trustable
    if (sensor->getVolt() < 0.5) {
         labelPressureValues[sensor->getOrdinal()]->setPalette(*redText);
    } else {
        labelPressureValues[sensor->getOrdinal()]->setPalette(*normalText);
    }
}

void View::redraw(){
    xValue = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;

    // TODO get maxnumberofSensors

    //qDebug() << "ReDraw " << ui->customPlot->graphCount() << " graphs";
    ui->customPlot->graph(0)->removeDataBefore(xValue-plotXRange);
    ui->customPlot->graph(0)->rescaleValueAxis(false);

    for (int i = 1; i < ui->customPlot->graphCount(); i++){
        ui->customPlot->graph(i)->removeDataBefore(xValue-plotXRange);
        ui->customPlot->graph(i)->rescaleValueAxis(true);
    }

    ui->customPlot->xAxis->setRange(xValue, plotXRange, Qt::AlignRight);
    ui->customPlot->replot();
}

void View::setupEvacuateTabLabelsAndButtons() {
    ui->gridLayout_evacuateTab->addWidget(horizontalLine[3],2,0,1,3);
    ui->gridLayout_evacuateTab->addWidget(horizontalLine[4],2,3,1,4);
    for (int i = 0; i < 14; i++) {
        labelEvacuateText[i] = new QLabel("Connector " + QString::number(i+1));
        btnEvacuate[i] = new QPushButton("Evacuate");
        btnEvacuate[i]->setObjectName(QString::number(i));
        labelEvacuateText[i]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    }
    for (int i = 0; i < 6; i++) {
        ui->gridLayout_evacuateTab->addWidget(labelEvacuateText[i],0,i);
        ui->gridLayout_evacuateTab->addWidget(btnEvacuate[i],1,i);
        ui->gridLayout_evacuateTab->addWidget(labelEvacuateText[i+6],3,i);
        ui->gridLayout_evacuateTab->addWidget(btnEvacuate[i+6],4,i);
    }
    // setup ref 1 and 2
    labelEvacuateText[12]->setText(tr("Ref 1"));
    ui->gridLayout_evacuateTab->addWidget(labelEvacuateText[12],0,6);
    ui->gridLayout_evacuateTab->addWidget(btnEvacuate[12],1,6);
    labelEvacuateText[13]->setText(tr("Ref 2"));
    ui->gridLayout_evacuateTab->addWidget(labelEvacuateText[13],3,6);
    ui->gridLayout_evacuateTab->addWidget(btnEvacuate[13],4,6);
}

void View::setupPrepressureTabLabelsAndButtons() {
    ui->gridLayout_prepressureTab->addWidget(horizontalLine[5],2,0,1,4);
    ui->gridLayout_prepressureTab->addWidget(horizontalLine[6],2,3,1,4);

    for (int i = 0; i < 14; i++) {
        labelPrepressureText[i] = new QLabel("Connector " + QString::number(i+1));
        btnPrepressure[i] = new QPushButton("Set prepressure");
        btnPrepressure[i]->setObjectName(QString::number(i));
        labelPrepressureText[i]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    }
    for (int i = 0; i < 6; i++) {
        ui->gridLayout_prepressureTab->addWidget(labelPrepressureText[i],0,i);
        ui->gridLayout_prepressureTab->addWidget(btnPrepressure[i],1,i);
        ui->gridLayout_prepressureTab->addWidget(labelPrepressureText[i+6],3,i);
        ui->gridLayout_prepressureTab->addWidget(btnPrepressure[i+6],4,i);
    }
    // setup ref 1 and 2
    labelPrepressureText[12]->setText(tr("Ref 1"));
    ui->gridLayout_prepressureTab->addWidget(labelPrepressureText[12],0,6);
    ui->gridLayout_prepressureTab->addWidget(btnPrepressure[12],1,6);
    labelPrepressureText[13]->setText(tr("Ref 2"));
    ui->gridLayout_prepressureTab->addWidget(labelPrepressureText[13],3,6);
    ui->gridLayout_prepressureTab->addWidget(btnPrepressure[13],4,6);
}


void View::setSensorVisible(int ordinal, bool state){
    //qDebug() << "Set visible sensor" << ordinal << ": " << state;
    if (state){
        ui->customPlot->graph(ordinal)->addToLegend();
    } else {
        ui->customPlot->graph(ordinal)->removeFromLegend();
    }
    ui->customPlot->graph(ordinal)->setVisible(state);

    ui->customPlot->legend->setVisible(ui->customPlot->legend->itemCount() > 0);
}

void View::setupHorizontalLines() {
    for (int i = 0; i < 7; i++) {
        horizontalLine[i] = new QFrame();
        horizontalLine[i]->setObjectName(QString::fromUtf8("line")+QString::number(i));
        horizontalLine[i]->setGeometry(QRect(320, 150, 118, 3));
        horizontalLine[i]->setFrameShape(QFrame::HLine);
        horizontalLine[i]->setFrameShadow(QFrame::Sunken);

    }
    ui->gridLayout_pressureTab->addWidget(horizontalLine[0],2,0,1,3);
    ui->gridLayout_pressureTab->addWidget(horizontalLine[1],2,3,1,3);
    ui->gridLayout_pressureTab->addWidget(horizontalLine[2],2,6,1,2);
}

void View::setupPressureTabLabels() {
    for (int i = 0; i < 16; i++) {
        labelPressureText[i] = new QLabel("Connector " + QString::number(i+1) + "\n[mbar]");
        labelPressureValues[i] = new QLabel(QString::number(0.00));
        labelPressureText[i]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        labelPressureValues[i]->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    }
    for (int i = 0; i < 6; i++) {
        ui->gridLayout_pressureTab->addWidget(labelPressureText[i],0,i);
        ui->gridLayout_pressureTab->addWidget(labelPressureValues[i],1,i);
        ui->gridLayout_pressureTab->addWidget(labelPressureText[i+6],3,i);
        ui->gridLayout_pressureTab->addWidget(labelPressureValues[i+6],4,i);
    }
    // Reference 1 & 2
    labelPressureText[12]->setText("Channel Ref 1\n[mbar]");
    labelPressureText[13]->setText("Channel Ref 2\n[mbar]");
    ui->gridLayout_pressureTab->addWidget(labelPressureText[12],0,6);
    ui->gridLayout_pressureTab->addWidget(labelPressureValues[12],1,6);
    ui->gridLayout_pressureTab->addWidget(labelPressureText[13],0,7);
    ui->gridLayout_pressureTab->addWidget(labelPressureValues[13],1,7);
    // Temperature and absolute pressure
    labelPressureText[14]->setText("Temperature\n[°C]");
    labelPressureText[15]->setText("Absolute Pressure\n[Bar]");
    ui->gridLayout_pressureTab->addWidget(labelPressureText[14],3,6);
    ui->gridLayout_pressureTab->addWidget(labelPressureValues[14],4,6);
    ui->gridLayout_pressureTab->addWidget(labelPressureText[15],3,7);
    ui->gridLayout_pressureTab->addWidget(labelPressureValues[15],4,7);
}

int View::showEvacuationDialog() {
    QMessageBox msgBox;
    msgBox.setText("Evacuation process initiated.");
    msgBox.setInformativeText("Please empty the bottle first and press ok!");
    msgBox.setStandardButtons(QMessageBox::Ok |  QMessageBox::Cancel);
    msgBox.setDefaultButton(QMessageBox::Ok);
    return msgBox.exec();
}

int View::showPrepressureDialog(double pressure) {
    QMessageBox msgBox;
    msgBox.setText("Setting prepressure.");
    msgBox.setInformativeText("Make sure that the prepressure is set to the bottle!"
                              "Is the current pressure ca. " + QString::number(pressure) + " ?");
    msgBox.setStandardButtons(QMessageBox::Yes |  QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::Yes);
    return msgBox.exec();
}

void View::receiveAbsolutePressureValue(double value) {
    labelPressureValues[15]->setText(QString::number(value,'f',3));
}
void View::receiveTemperature(double value) {
    labelPressureValues[14]->setText(QString::number(value,'f',3));
}
